<template>
  <a-card>
    <a-row :gutter="24">
      <a-col :md="6" :sm="24">
        <a-card hoverable style="height: 600px; overflow-y: auto">
          <a-tree :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" v-model="checkedKeys" @select="onSelect" :selectedKeys="selectedKeys" :treeData="treeData" :replaceFields="replaceFields" />
        </a-card>
      </a-col>
      <a-col :md="18" :sm="24">
        <div class="table-page-search-wrapper" style="margin-bottom: 16px">
          <a-row>
            <a-col :md="6" :sm="24">
              <a-form-item v-bind="formItemLayout" label="姓名">
                <a-input placeholder v-model="queryParam.trueName" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item v-bind="formItemLayout" label="登录名">
                <a-input placeholder v-model="queryParam.userName" />
              </a-form-item>
            </a-col>
            <!-- <a-col :md="6" :sm="24">
                <a-form-item v-bind="formItemLayout" label="账号状态">
                  <a-radio-group @change="onChange" v-model="value">
                    <a-radio :value="1">启用</a-radio>
                    <a-radio :value="2">禁用</a-radio>
                  </a-radio-group>
                </a-form-item>
            </a-col>-->
          </a-row>
          <a-row>
            <a-button type="primary" class="actionButton" @click="search">查询</a-button>
            <a-button type="primary" class="actionButton" @click="add">添加</a-button>
            <a-popconfirm title="确定禁用?" okText="确定" cancelText="取消" @confirm="disable">
              <a-button type="primary" class="actionButton">禁用</a-button>
            </a-popconfirm>
            <a-button type="primary" class="actionButton" @click="nodisable">启用</a-button>
            <a-button type="primary" class="actionButton" @click="reset">重置密码</a-button>
            <a-popconfirm v-if="isAdmin()" title="确定删除?" okText="确定" cancelText="取消" @confirm="del">
              <a-button type="primary" class="actionButton">删除</a-button>
            </a-popconfirm>
          </a-row>
        </div>
        <a-spin :spinning="spinning" tip="获取数据中...">
          <div class="spin-content">
            <a-table size="small" bordered :rowKey="(record) => record.id" :columns="columns" :dataSource="data" :pagination="pagination" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :rowClassName="setRowClassName">
              <span slot="IsDisabled" slot-scope="IsDisabled">
                <a-tag :color="IsDisabled === false ? 'green' : 'red'" :key="IsDisabled">{{ IsDisabled === false ? '启用' : '禁用' }}</a-tag>
              </span>
              <span slot="action" slot-scope="text, record">
                <template>
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>修改</span>
                    </template>
                    <span size="small" type="link" @click="handleEdit(record)" style="cursor: pointer; color: #1890ff">修改</span>
                  </a-tooltip>
                  <a-divider type="vertical" />
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>关联部门</span>
                    </template>
                    <span size="small" type="link" @click="handleDepart(record)" style="cursor: pointer; color: #1890ff">关联部门</span>
                  </a-tooltip>
                </template>
              </span>
            </a-table>
          </div>
        </a-spin>
      </a-col>
    </a-row>
    <!-- 修改 -->
    <a-modal :title="title" :visible="visible" @cancel="handleCancel" :footer="null" :centered="true">
      <div class="waterArea" style="background-color: #fff">
        <a-spin :spinning="loading">
          <a-form :form="form">
            <a-form-item v-bind="formItemLayout" label="姓名">
              <a-input v-decorator="['TrueName', { rules: [{ required: true, message: '请填写姓名!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="登录名">
              <a-input v-decorator="['UserName', { rules: [{ required: true, message: '请填写登录名!' }] }]" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="密码">
              <!-- <a-input type="password" v-decorator="['Password', { rules: [{ required: true, message: '请填写密码!' }] }]" /> -->
              <a-input
                type="password"
                v-decorator="[
                  'Password',
                  {
                    rules: [
                      { required: true, message: '请填写密码!' },
                      { pattern: regex, message: '密码需包含数字、大小写字母、特殊字符，长度8-20，不能出现连续的相同字母或数字、不能出现顺序的字母或数字，不能使用手机号或邮箱作为密码' },
                    ],
                  },
                ]"
              />
              <!-- <span style="font-size: 12px;color: #666666">
                密码需包含数字、大小写字母、特殊字符，长度8-20。
              </span> -->
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="所属部门">
              <treeselect :show-count="true" :options="Dept" v-model="deptValue" placeholder="请选择工作部门..." :normalizer="normalizer" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="手机号">
              <a-input v-decorator="['Phone']" />
            </a-form-item>
            <!-- <div style="margin-bottom:16px">
              <div class="tree-select-label-YH" style="width:23%">
                <span>工作部门:</span>
              </div>
              <treeselect style="width:75%" class="tree-select-self-YH" :show-count="true" :options="Dept" v-model="deptValue" placeholder="请选择工作部门..." :normalizer="normalizer" />
            </div> -->

            <a-form-item v-bind="formItemLayout" label="状态">
              <a-switch v-model="IsDisabled" checkedChildren="启用" unCheckedChildren="禁用" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="是否管理员">
              <a-switch v-decorator="['IsAdmin', { valuePropName: 'checked' }]" checkedChildren="是" unCheckedChildren="否" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="角色">
              <a-radio-group @change="onChange" v-model="roleId">
                <a-radio v-for="item in roleList" :value="item.ID" :key="item.ID">{{ item.RoleName }}</a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item v-bind="formItemLayout" label="备注">
              <a-input v-decorator="['Remark']" />
            </a-form-item>
            <a-form-item v-bind="formItemLayout1" style="text-align: center; margin-bottom: 0">
              <a-button type="primary" @click="ok">确定</a-button>
            </a-form-item>
          </a-form>
        </a-spin>
      </div>
    </a-modal>
    <!-- 关联部门 -->
    <a-modal :title="'部门'" :visible="visibleDepart" :width="600" @cancel="handleCancelDepart" :footer="null" :centered="true">
      <a-tree :showLine="true" @expand="onExpand" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" :default-selected-keys="defaultCheckedDepartKeys" :default-checked-keys="defaultCheckedDepartKeys" :checkable="true" v-model="checkedDepartKeys" @check="onCheckDepart" :selectedKeys="selectedDepartKeys" :treeData="treeData" :replaceFields="replaceFields" />
      <!-- <a-button type="primary" @click="okDepart">确定</a-button> -->
    </a-modal>
  </a-card>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { getUserByID, getUserList, deleteUsers, reSetPassword, saveUser, setEnable, setDisabled, getListByUserID, SaveUserDepartment, DeleteUserDepartmentByID } from '@/api/user'
import { deleteChildrenIfNull } from '@/utils/util'
import { getRoleList } from '@/api/role'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import '@/views/treeselect1.css'
import { authDevice } from '@/utils/mixin'
export default {
  mixins: [authDevice],
  components: {
    Treeselect,
  },
  data() {
    return {
      regex: /^(?=.*\d)(?!.*(\d)\1{2})(?!.*(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210))(?=.*[a-z])(?=.*[A-Z])(?=.*[^\da-zA-Z\s]).{8,20}$/,
      title: '添加人员',
      action: 'add',
      visible: false,
      visibleDepart: false,
      expandedKeys: [],
      IsDisabled: true,
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      checkedDepartKeys: [],
      checkedDepartKeysData: [],
      defaultCheckedDepartKeys: [],
      selectedDepartKeys: [],
      userDeparts: [],
      treeData: [],
      data: [],
      roleList: [],
      selectedRowKeys: [],
      replaceFields: {
        key: 'id',
      },
      value: null,
      queryParam: {},
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children,
        }
      },
      pagination: {
        onChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        current: 1,
        total: 0,
        showQuickJumper: true,
        size: 'small',
        defaultPageSize: 10,
        showTotal: (total) => `共 ${total} 条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],
        onShowSizeChange: (index, pageSize) => {
          this.pageOnChange(index, pageSize)
        },
        position: 'top',
      },
      spinning: false,
      // 表头
      columns: [
        {
          title: '姓名',
          dataIndex: 'TrueName',
          key: 'TrueName',
          align: 'center',
        },
        {
          title: '登录名',
          dataIndex: 'UserName',
          key: 'UserName',
          align: 'center',
        },
        {
          title: '账号状态',
          dataIndex: 'IsDisabled',
          key: 'IsDisabled',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'IsDisabled' },
        },
        {
          title: '角色',
          dataIndex: 'RoleName',
          key: 'RoleName',
          align: 'center',
        },
        {
          title: '所属部门',
          dataIndex: 'DepartmentName',
          key: 'DepartmentName',
          width: 100,
          align: 'center',
        },
        {
          title: '手机号',
          dataIndex: 'Phone',
          key: 'Phone',
          width: 120,
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          width: 140,
          align: 'center',
        },
      ],
      loading: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 0 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
      },
      Dept: [],
      deptValue: null,
      ParentId: null,
      roleId: null,
      ParentName: null,
      currentId: null,
      actionData: {},
    }
  },
  watch: {
    checkedKeys(val) {
      console.log('onCheck', val)
    },
  },
  created() {
    getDepartmentList().then((res) => {
      this.treeData = res.children
      this.Dept = res.children
      this.removeChildrenIfNUll(this.Dept)
    })
    // getDepartmentList().then((res) => {
    //   this.Dept = res.data.children
    //   this.removeChildrenIfNUll(this.Dept)
    // })
    getRoleList().then((res) => {
      this.roleList = res
    })
    this.initData(this.queryParam)
  },
  methods: {
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    removeChildrenIfNUll(data) {
      data.map((a) => {
        if (a && a.children.length > 0) {
          this.removeChildrenIfNUll(a.children)
        } else {
          deleteChildrenIfNull(a)
        }
      })
    },
    initData(data) {
      this.spinning = true
      getUserList(data)
        .then((res) => {
          if (res.success) {
            this.data = res.data
            this.pagination.total = res.page.RecordCount
          } else {
            this.$message.error(res.message)
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    search() {
      var _this = this
      _this.queryParam = Object.assign({}, _this.queryParam, { index: 1 })
      this.pagination.current = 1
      _this.initData(_this.queryParam)
    },
    add() {
      this.title = '添加人员'
      this.action = 'add'
      this.visible = true
      this.roleId = null
      this.form.resetFields()
    },
    onChange() {},
    ok() {
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        if (this.deptValue == null) {
          this.$message.info('请输入部门!')
          return
        }
        if (!errors) {
          this.loading = true
          setTimeout(() => {
            // console.log(this.$store.getters.token.id)
            console.log(this.roleId)
            const value = {
              ...values,
              id: this.currentId,
              DepartmentID: this.deptValue,
              IsDisabled: !this.IsDisabled,
              RoleId: this.roleId,
              AddUserID: this.action === 'add' ? this.$store.getters.token.id : null,
              ModUserID: this.action === 'edit' ? this.$store.getters.token.id : null,
            }
            saveUser(value).then((res) => {
              this.initData(this.queryParam)
              this.loading = false
              this.visible = false
              this.currentId = null
            })
          }, 1000)
        } else {
        }
      })
    },
    del() {
      console.log(this.selectedRowKeys)
      deleteUsers(this.selectedRowKeys).then((res) => {
        this.initData(this.queryParam)
        this.selectedRowKeys = []
      })
    },
    disable() {
      console.log(this.selectedRowKeys)
      setDisabled(this.selectedRowKeys).then((res) => {
        this.initData(this.queryParam)
      })
    },
    nodisable() {
      console.log(this.selectedRowKeys)
      setEnable(this.selectedRowKeys).then((res) => {
        this.initData(this.queryParam)
      })
    },
    reset() {
      reSetPassword(this.selectedRowKeys).then((res) => {
        this.initData(this.queryParam)
      })
    },
    handleEdit(data) {
      this.title = '修改用户'
      this.action = 'edit'
      getUserByID({ userid: data.id }).then((res) => {
        this.visible = true
        setTimeout(() => {
          this.currentId = data.id
          this.roleId = data.RoleID
          this.IsDisabled = !data.IsDisabled
          this.form.setFieldsValue({ TrueName: data.TrueName })
          this.form.setFieldsValue({ UserName: data.UserName })
          this.form.setFieldsValue({ Phone: data.Phone })
          this.deptValue = data.DepartmentID
          // this.form.setFieldsValue({ IsDisabled: !data.IsDisabled })
          this.form.setFieldsValue({ Password: data.Password })
          this.form.setFieldsValue({ Remark: data.Remark })
        }, 500)
      })
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect(selectedKeys, e) {
      this.ParentName = e.selectedNodes.length > 0 ? e.selectedNodes[0].data.props.name : this.ParentName
      console.log(e.selectedNodes)
      this.selectedKeys = selectedKeys
      this.ParentId = selectedKeys[0]
      Object.assign(this.queryParam, { deptID: selectedKeys[0] })
      this.initData(this.queryParam)
    },
    handleCancel() {
      this.visible = false
    },
    setRowClassName(record, idx) {
      return idx % 2 === 1 ? 'bg-row' : ''
    },
    handleCancelDepart() {
      this.visibleDepart = false
    },
    pageOnChange(index, pageSize) {
      this.spinning = true
      Object.assign(this.pagination, {
        current: index,
        pageSize,
        index,
      })
      Object.assign(this.queryParam, {
        pageSize,
        index,
      })
      this.initData(this.queryParam)
    },

    async handleDepart(data) {
      this.visibleDepart = true
      this.actionData = await data
      this.initUserDepartData()
    },
    initUserDepartData() {
      const data = this.actionData
      getListByUserID({ userID: data.id }).then(async (res) => {
        const data = await res.data
        const ary = []
        data.forEach((d) => {
          ary.push(d.departmentID)
          this.checkedDepartKeysData.push(d)
        })
        this.defaultCheckedDepartKeys = ary
        this.checkedDepartKeys = ary
      })
    },
    okDepart() {
      this.visibleDepart = false
      this.checkedDepartKeys = []
      this.checkedDepartKeysData = []
    },
    async onCheckDepart(checkedKeys, e) {
      const defaultCheckedDepartKeys = this.defaultCheckedDepartKeys
      if (checkedKeys.length > defaultCheckedDepartKeys.length) {
        const ary = checkedKeys.filter((v) => !defaultCheckedDepartKeys.some((s) => s === v))
        const param = {
          userid: this.actionData.id,
          departmentid: ary.join(','),
        }
        SaveUserDepartment(param).then(() => {
          this.$message.success('操作成功!')
          this.initUserDepartData()
        })
      }
      if (checkedKeys.length < defaultCheckedDepartKeys.length) {
        const ary = defaultCheckedDepartKeys.filter((v) => !checkedKeys.some((s) => s === v))
        let id = ''
        this.checkedDepartKeysData.forEach((d) => {
          if (d.departmentID == ary.join(',')) {
            id = d.id
          }
        })
        const param = {
          userDepartmentID: id,
        }
        DeleteUserDepartmentByID(param).then(() => {
          this.$message.success('操作成功!')
          this.initUserDepartData()
        })
      }
    },
  },
}
</script>

<style lang="less" scoped>
.actionButton {
  margin-left: 10px;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.tree-select-label-YH {
  display: inline-block;
  height: 30px;
  vertical-align: bottom;
  text-align: right;
}

.tree-select-self-YH {
  display: inline-block;
  width: 200px;
  margin-left: 8px;
}
</style>
